package top.shaozuo.simple.user.service.impl;

import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import javax.validation.Validator;

import top.shaozuo.simple.user.domain.User;
import top.shaozuo.simple.user.repository.UserRepository;
import top.shaozuo.simple.user.service.UserService;

public class UserServiceImpl implements UserService {

    //不能直接这么处理，当 UserServiceImpl 实例化的时候还没有 DatabaseUserRepository

    @Resource(name = "bean/UserRepository")
    private UserRepository userRepository;

    @Resource(name = "bean/Validator")
    private Validator validator;

    @Override
    public boolean register(User user) {
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        if (!violations.isEmpty()) {
            String messages = violations.stream()
                    .map(cv -> cv == null ? "null" : cv.getPropertyPath() + ": " + cv.getMessage())
                    .collect(Collectors.joining(", "));
            throw new RuntimeException(new ValidationException("校验错误:" + messages));
        }
        return userRepository.save(user);
    }

    @Override
    public boolean deregister(User user) {
        return userRepository.deleteById(user.getId());
    }

    @Override
    public boolean update(User user) {
        return userRepository.save(user);
    }

    @Override
    public User queryUserById(Long id) {
        return userRepository.getById(id);
    }

    @Override
    public User queryUserByNameAndPassword(String name, String password) {
        return userRepository.getByNameAndPassword(name, password);
    }

    @Override
    public User queryUserByEmail(String email) {
        return userRepository.getByEmail(email);
    }

}
